//
//  Client_RF225_MoveInvByArtController.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/9/10.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_MoveInvByArtController:  HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate , HDNumberInputCellDelegate{
    //MARK: - property
    let dataArray:[[String]] = [
        ["移出货位","品项数"],
        ["货品条码","货品名称","规格/库存"],
        ["整件/零散","移入货位"]
    ]
    var piFromBin: String?
    var piPalletCode: String?
    var dateInProduce: Date?
    var piToBin: String?
    var darray : [[String : String]]?
    var endFlag : Bool = false
    var piQtyStr = ""
    
    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: [ "清屏" ])
        return view
    }()
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDNumberInputCell.self, forCellReuseIdentifier: "HDNumberInputCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        super.viewDidLoad()
    }
    override func viewDidAppear(_ animated: Bool) {
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as! HDBarcodeInputCell
        cell.state = inputViewState.activated
        self.activedCell = cell
    }
    //MARK: - delegate
    func finishNumInput(_ cell: HDNumberInputCell) {
        if cell.titleView.text == "批号/日期"{
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
                self.showMessage("输入的批号不合法", success: false)
                return
            }
        }
        if cell.titleView.text == "整件/零散" {
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
                self.showMessage("输入的整件数不合法", success: false)
                return
            }
            if Double(cell.bagNumberTextField.text ?? "0.0") == nil{
                self.showMessage("输入的零散数不合法", success: false)
                return
            }
        }
        let indexPath = self.tableView.indexPath(for: cell)
        switch (indexPath! as NSIndexPath).row {
        case 0:
            self.goNextCell(cell, nextInsexPath: IndexPath(item: 1, section: 2))
            piQtyStr = (cell.boxNumberTextField.text ?? "0") + "+" + (cell.bagNumberTextField.text ?? "0")//保存最新的件数
        default:
            break
        }
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    
    func clickFounctionBottom(_ position: NSInteger) {
        switch position {
        case 0:
            let firstCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! HDBarcodeInputCell
            if firstCell.codeInputView.textField.text?.characters.count == 0 {
                return
            }

            let alertController = UIAlertController(title: "提示", message: "确定清除所有信息？", preferredStyle: UIAlertControllerStyle.alert)
            alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
            alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
                self.resetController(self.activedCell!, nextItem: 0, nextSection: 0, message: nil, success: true)
            }))
            self.present(alertController, animated: true, completion: nil)
            break
        default:
            break
        }
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        switch (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row  {
        case 0: //第一个cell回车
            guard cell.codeInputView.textField.text?.characters.count > 0 else{
                self.showMessage("请输入移出货位", success: false)
                return
            }
            let cellText = cell.codeInputView.textField.text!
            self.getData(["piFromBin":cellText,"piOperator":(userInfo?.userName)!], bodyMethod: "chkBinRtnArt", suffix: "330", success: { (dict) in
                self.oneToManyHandler(self.downloadData["poArticleCode"]!, piOwner: nil, piBin: cellText, success: { (dict) in
                    self.getCollection(["piBin":cellText], bodyMethod: "MoveInv_GetArtListByBin", suffix: nil, success: { (dict, collections) in
                        self.piFromBin = cellText
                        //展示cell的方法
                        let cell1 = self.tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as! HDProductInfocell
                        cell1.textField.text = self.downloadData["poArtCount"]
                        var dictDis : [String : String]?
                        if collections.count  == 1 {  //只有一个货品的话
                            dictDis = collections.first
                            self.showInfo(cell, dictDis: dictDis)
                        }else if collections.count > 1{
                            let selectorView = SelectTableView(dataArray: collections)
                            cell.endEditing(true)
                            selectorView.showSelector(self.tableView, success: { (dict) in
                                dictDis = dict
                                self.showInfo(cell, dictDis: dictDis)
                            })
                        }
                        }, failed: {
                            cell.state = inputViewState.wrong
                    })

                    }, failed: {
                         cell.state = inputViewState.wrong
                })

                }, failed: {_ in 
                    cell.state = inputViewState.wrong
                    
            })
            
        case 201:
            guard cell.codeInputView.textField.text?.characters.count > 0 else{
                self.showMessage("请输入移入货位", success: false)
                return
            }
            let cellText = cell.codeInputView.textField.text!
            self.getData(["piFromBin":self.piFromBin!,"piToBin":cellText,"piArticle":self.downloadData["货品内码"]!,"piQtyStr":self.piQtyStr,"piOperator":(userInfo?.userName)!], bodyMethod: "updMoveInvArticle", suffix: nil, success: { (dict) in
                self.piToBin = cellText
                self.resetController(cell, nextItem: 0, nextSection: 0, message: "货品移库成功", success: true)
                }, failed: {_ in 
                    cell.state = inputViewState.wrong
            })
            break
        default:
            break
        }
        
    }
    //MARK: - private
    func showInfo(_ cell:HDBarcodeInputCell , dictDis: [String : String]?){
        self.downloadData += dictDis!
        for i in 0...2 { //给需要的地方赋值
            let procell = self.tableView.cellForRow(at: IndexPath(item: i, section: 1)) as! HDProductInfocell
            switch i {
            case 0:
                procell.textField.text = dictDis!["货品代码"]
            case 1:
                procell.textField.text = dictDis!["货品"]
            case 2:
                procell.textField.text = (dictDis!["规格"] ?? "0")  + "/" + (dictDis!["件数"] ?? "0")
            default:
                break
            }
        }
        
        self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 2))
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDNumberInputCell
        let  s = self.downloadData["件数"]
        let arr = s!.components(separatedBy: "+")
        if arr.count <= 1  {
            cell.bagNumberTextField.text = "0"
            cell.boxNumberTextField.text = arr.first
        }else{
            cell.boxNumberTextField.text = arr.first
            cell.bagNumberTextField.text = arr.last
        }
       
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 100 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
        case 1:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        case 100..<103:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
        case 200:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDNumberInputCell") as! HDNumberInputCell
            let cell = cellOriginal as! HDNumberInputCell
            cell.precisionBox = 0
            cell.precisionBag = 2
            cell.delegate = self
        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
            cellOriginal?.clearContent()
        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        cellOriginal!.titleView.text = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        return cellOriginal!
    }
    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 2:
            return UIView(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 0.1))
        default:
            return nil
        }
    }
}
